$(document).ready(function(){

	initShopCart();
	//勾选
    $(".checkLabel").click(function(){
    	var flag = $(this).prev().is(':checked');
    	if(flag){
            $(this).prev().attr("checked",false);
            $("#buy-sele-all").attr("checked", false); //将全选勾除
            $("#buy-sele-all").val(0);

        }else{
            $(this).prev().attr("checked",true);
            //如果全部都选中了，将全选勾选
            var groupUL = $(".container").find("ul[class='list-group']").get();
            var checkUL = $(".container").find("div[class='icheck pull-left mr5'] :checkbox:checked").get();
            if(groupUL.length == checkUL.length){
            	$("#buy-sele-all").attr("checked", true);
            	$("#buy-sele-all").val(1);
            }
        }

      //计算总价
	  calculateTotal();
    });
    updateProductSelectStatus(null);
    // 全选，全不选
    $("#buy-sele-all").click(function() {
        var flag = $(this).val();
        if(flag ==1){
            $(this).val(0);
             $(".ids").attr("checked", false);
        }else{
            $(this).val(1);
            $(".ids").attr("checked", true);
        }

      //计算总价
  	  calculateTotal();
    });

	  //计算总价
	 calculateTotal();
});
//初始化购物车商品
function initShopCart(){
	var shopCartInfo=jQuery.getCookie("shopCartInfo");
	if(shopCartInfo==""){
		$("#productsInfo").html(String.formatmodel(templete.getShopCartNullTemp(),{}));
	}else{
		$("#productsInfo").html("");
		shopCartInfo= JSON.parse(shopCartInfo);
		for(var i=0;i<shopCartInfo.length;i++){
			//console.log(shopCartInfo[i]);
			$("#productsInfo").append(String.formatmodel(templete.getShopCartTeml(),shopCartInfo[i]));
		}
	}
}

//相加
function increase(obj){
	var _this = $(obj);
	var _count_obj=_this.prev();
	var count =Number($(_count_obj).val());
	var prod_id=$(_count_obj).attr("prodId");

    var _num=parseInt(count)+1;
	var re = /^[1-9]+[0-9]*]*$/;
	if( isNaN(_num) || ! re.test(_num)) {
	 	return ;
	}else if(_num==9999){
		return;
	}
	var result = changeShopCartNumber(_num,prod_id,1);
	if(result){
		$(_count_obj).val(count*1+1);
		//计算总价
		calculateTotal();
	}

}

//减
function disDe(obj){
	var _this = $(obj);
	var _count_obj=_this.next();
	var count =Number($(_count_obj).val());
	//var basket_id=$(_count_obj).attr("itemkey");
	var prod_id=$(_count_obj).attr("prodId");
	//var sku_id=$(_count_obj).attr("skuId");
	var _num=parseInt(count)-1;

	var re = /^[1-9]+[0-9]*]*$/;
	if( isNaN(_num) || ! re.test(_num)) {
	 	return ;
	}else if(_num==0){
		return ;
	}
	var result = changeShopCartNumber(_num,prod_id,1);
	if(result){
		$(_count_obj).val(count*1-1);
		//计算总价
		calculateTotal();
	}
}
//更新购物车商品数量
function changeShopCartNumber(_num,_prodId,type){
	//console.log(_num);
	//console.log(_prodId);
	var config = true;
	var shopCartInfo=jQuery.getCookie("shopCartInfo");
	if(shopCartInfo==""){
		floatNotify.simple("操作失败！");
	}else{
		shopCartInfo=JSON.parse(shopCartInfo);
		for(var i=0;i<shopCartInfo.length;i++){//console.log(shopCartInfo[i]);
			if(shopCartInfo[i].id==_prodId){
				shopCartInfo[i].quantity=_num;
			}
		}
		jQuery.setCookie("shopCartInfo",JSON.stringify(shopCartInfo),null);
	}

	return config;
}

//计算总价
function calculateTotal(){
	var allCash = 0;
	var list = $(".container").find("ul[class='list-group']").get();
	for(var i=0;i<list.length;i++){
		var selected = $(list[i]).find("div[class='icheck pull-left mr5']>:checkbox").is(":checked");
		if(selected){
			var cash = $(list[i]).find("em[class='red productTotalPrice']").html().substring(1);//取单价
			var count = $(list[i]).find("input[class='btn gary2 Amount']").val();//取数量
			if(cash.indexOf(",")!=-1){
				//格式化还原数字
				cash=cash.replace(",","");
			}
			allCash += Number(cash)*Number(count);
		}
	}
	allCash = Math.round(Number(allCash)*100)/100;
	var pos_decimal = allCash.toString().indexOf('.');
	if (pos_decimal < 0)
	{
		allCash += '.00';
	}
	$("#totalPrice").html(allCash);
}

//删除购物车商品
function deleteShopCart(_prodId,_basketName){
	if(confirm("温馨提示","删除后不可恢复, 确定要删除'"+_basketName+"'吗？")){
		var shopCartInfo=jQuery.getCookie("shopCartInfo");
		if(shopCartInfo==""){
			floatNotify.simple("操作失败！");
		}else{
			shopCartInfo=JSON.parse(shopCartInfo);
			var shopCartInfoChange=[];
			for(var i=0;i<shopCartInfo.length;i++){
				if(shopCartInfo[i].id!=_prodId){
					shopCartInfoChange.push(shopCartInfo[i]);
				}
			}
			jQuery.setCookie("shopCartInfo",JSON.stringify(shopCartInfoChange),null);
		}
		initShopCart();
		calculateTotal();
	}
}

//结算选中商品
function submitShopCart(){
	//cartToOrder.html;
	var array = $(".ids:checked").get();
	if(array.length==0){
		floatNotify.simple("请选择要结算的商品");
		return;
	}

    var shopCartStr = "";
	for(var i in array){
		//console.log($(array[i]).attr("itemkey"));
		shopCartStr+=$(array[i]).attr("itemkey")+",";
		/*if(i!=0){
			shopCartStr =shopCartStr+",";
		}
		var basket_id = $(array[i]).attr("itemkey");
		shopCartStr=shopCartStr + basket_id;*/
	}
	//console.log(shopCartStr);
	updateProductSelectStatus(shopCartStr);
	window.location.href="cartToOrder.html";
	//调用方法
	//abstractForm(contextPath+'/p/orderDetails', shopCartStr);
}

function abstractForm(URL, shopCartIds){
	   var temp = document.createElement("form");
	   temp.action = URL;
	   temp.method = "post";
	   temp.style.display = "none";
	   var opt = document.createElement("textarea");
	   opt.name = 'shopCartItems';
	   opt.value = shopCartIds;
	   temp.appendChild(opt);
	   document.body.appendChild(temp);
	   temp.submit();
	   return temp;
}
//更新cookie购物车中商品被选择选择的情况
function updateProductSelectStatus(ids){
	//console.log(ids);
	var shopCartInfo=jQuery.getCookie("shopCartInfo");
	if(shopCartInfo==""||ids==""){
		return;
	}
	shopCartInfo=JSON.parse(shopCartInfo);

	for(var i in shopCartInfo){//初始化状态
		shopCartInfo[i].select=false;
	}
	//console.log(shopCartInfo);
	if(ids!=null&&ids!=""&&ids!=undefined){//选中状态的添加
		var pIds=ids.split(",");
		for(var i in pIds){
			for(var j in shopCartInfo){
				if(pIds[i]==shopCartInfo[j].id){
					shopCartInfo[j].select=true;
				}
			}
		}
	}
	jQuery.setCookie("shopCartInfo",JSON.stringify(shopCartInfo),null);
}